package com.ktjy.service.impl;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * @param from    发件人
     * @param to      收件人
     * @param subject 主题
     * @param text    正文
     * @param cc      抄送人
     */
    public void sendMailWithoutAttachment(String from, String to,
                                          String subject, String text, String... cc) throws
            MessagingException {
        if (ObjectUtils.isEmpty(from)) {
            throw new RuntimeException("发送的邮箱配置为空, 不能发送邮件");
        }
        if (ObjectUtils.isEmpty(to)) {
            throw new RuntimeException("接收的邮箱配置为空, 不能发送邮件");
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
                true); //允许发送文件
        messageHelper.setFrom(from);//发件人
        messageHelper.setTo(to);//收件人
        if (cc != null && cc.length > 0) {
            messageHelper.setCc(cc);//抄送人
        }
        messageHelper.setSubject(subject);//主题
        messageHelper.setText(text, true);//内容 //允许发送html
        javaMailSender.send(mimeMessage);
    }

}
